package com.guguju.ssms.core.http;


import android.app.Application;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.guguju.ssms.Guguju;
import com.guguju.ssms.constant.IntentParms;
import com.guguju.ssms.core.log.LogUtil;
import com.guguju.ssms.feature.login.LoginActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.PostRequest;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by dell on 2022-5-14.
 */
public class HttpLoader {

    /**
     * init http loader
     *
     * @param context application context
     */
    public static void init(@NonNull Application context) {
        OkGo.init(context);//初始化
        try {
            HttpCommonHeader commonHeader = new HttpCommonHeader(context);
            OkGo.getInstance()
                    .setCertificates()//信任所有证书,不安全有风险
                    .addCommonHeaders(commonHeader);

            LogUtil.i("请求公共头信息:" + commonHeader.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 重新赋值header
     *
     * @param context application context
     */
    public static void refreshHeader(@NonNull Application context) {
        OkGo.getInstance().addCommonHeaders(new HttpCommonHeader(context));
    }

    /**
     * 取消所有请求
     */
    public static void cancelAll() {
        OkGo.getInstance().cancelAll();
    }

    /**
     * 根据url 取消请求
     *
     * @param tag 请求url来标识
     */
    public static void cancel(@NonNull String tag) {
        OkGo.getInstance().cancelTag(tag);
    }

    /**
     * post 请求数据
     *
     * @param url url
     */
    public static void post(@NonNull final String url) {
        post(url, null, false, null);
    }

    /**
     * post 请求数据
     *
     * @param url      url
     * @param callback callback
     */
    public static void post(@NonNull final String url, @NonNull final JsonCallback callback) {
        post(url, null, false, callback);
    }

    /**
     * post 请求数据
     *
     * @param url      url
     * @param callback callback
     * @param params   params
     */
    public static void post(@NonNull final String url, @NonNull JsonObject params, @NonNull final JsonCallback callback) {
        post(url, params, false, callback);
    }

    /**
     * post 请求数据
     *
     * @param url      url
     * @param params   params
     * @param callback callback
     * @param isSign   isSign
     */
    public static void post(@NonNull final String url, final JsonObject params, boolean isSign, final JsonCallback callback) {

        if (TextUtils.isEmpty(url)) {
            throw new IllegalArgumentException("url is empty");
        }

            LogUtil.i("请求url:" + url);

            PostRequest request = OkGo.post(url).tag(url);
            request.headers("Authorization", "Bearer " + Guguju.ASESSTOKEN);
            //request.headers("networkOperator", Guguju.NETWORKOPERATOR);
            //request.headers("appUserId", TextUtils.isEmpty(Guguju.USERID) ? "0" : Guguju.USERID);
            // request.headers("appAuth", Guguju.AUTH);

            if (params != null) {
                request.upJson(params.toString());
                LogUtil.i(params.toString());
            }

            request.execute(callback);
        //if (isSign) {
          //  request.headers("sign", genHeaderSign(params));
       // }
    }

    /**
     * post 上传图片
     *
     * @param url        url
     * @param paramsMaps params
     * @param callback   callback
     * @param fileName   fileName
     * @param file       file
     * @param isSign     isSign
     */
    public static void postFile(@NonNull final String url, HashMap<String, String> paramsMaps, boolean isSign, String fileName, File file, final JsonCallback callback) {

        if (TextUtils.isEmpty(url)) {
            throw new IllegalArgumentException("url is empty");
        }

        LogUtil.i("请求url:" + url);

        PostRequest request = OkGo.post(url).tag(url);

        request.params(fileName, file);

        //request.headers("netTranslateType", "");
        //request.headers("networkOperator", Guguju.NETWORKOPERATOR);
        //request.headers("appUserId", TextUtils.isEmpty(Guguju.USERID) ? "0" : Guguju.USERID);
        // request.headers("appAuth", Guguju.AUTH);


        if (paramsMaps != null) {
            String str = "";
            Set<String> keySet = paramsMaps.keySet();
            for (String key : keySet) {
                request.params(key, paramsMaps.get(key));
                str = str + key + ":" + paramsMaps.get(key) + ";";
            }
            LogUtil.i(str);
        }

       // if (isSign) {
          //  request.headers("sign", genHeaderSignMap(paramsMaps));
       // }

        request.execute(callback);
    }

    /**
     * post 微信请求数据
     *
     * @param url      url
     * @param callback callback
     */
    public static void postWX(@NonNull final String url, final StringCallback callback) {
        if (TextUtils.isEmpty(url)) {
            throw new IllegalArgumentException("url is empty");
        }
        LogUtil.i("请求url:" + url);
        PostRequest request = OkGo.post(url).tag(url);
        request.execute(callback);
    }


    /**
     * get 请求数据
     *
     * @param url url
     */
    public static void get(@NonNull final String url) {
        get(url, null, false, null);
    }

    /**
     * get 请求数据
     *
     * @param url      url
     * @param callback callback
     */
    public static void get(@NonNull final String url, @NonNull final JsonCallback callback) {
        get(url, null, false, callback);
    }

    /**
     * get 请求数据
     *
     * @param url      url
     * @param callback callback
     * @param params   params
     */
    public static void get(@NonNull final String url, @NonNull JsonObject params, @NonNull final JsonCallback callback) {
        get(url, params, false, callback);
    }


    /**
     * get 请求数据
     *
     * @param url      url
     * @param params   params
     * @param isSign   isSign
     * @param callback callback
     */
    public static void get(@NonNull final String url, final JsonObject params, boolean isSign, final JsonCallback callback) {
        if (TextUtils.isEmpty(url)) {
            throw new IllegalArgumentException("url is empty");
        }

        LogUtil.i("请求url:" + url);

        GetRequest request = OkGo.get(url).tag(url);

        if (params != null) {
            HttpParams httpParams = new HttpParams();
            Set<Map.Entry<String, JsonElement>> entrySet = params.entrySet();
            for (Map.Entry<String, JsonElement> entry : entrySet) {
                String key = entry.getKey();
                httpParams.put(key, params.get(key).getAsString());
            }
            request.params(httpParams);
            LogUtil.json(params.toString());
        }

      //  if (isSign) {
           // request.headers("sign", genHeaderSign(params));
      //  }

        request.execute(callback);
    }


    /**
     * 下载文件（图片,文件）
     *
     * @param url
     * @param fileCallback
     */
    public static void getFile(@NonNull final String url, final FileCallback fileCallback) {
        if (TextUtils.isEmpty(url)) {
            throw new IllegalArgumentException("url is empty");
        }

        LogUtil.i("请求url:" + url);
        GetRequest request = OkGo.get(url).tag(url);
        request.execute(fileCallback);
    }

    /**
     * @return params 大部分接口统一的参数集合
     */
    public static JsonObject getBaseHttpParams() {
        JsonObject params = new JsonObject();
        params.addProperty("userId", Guguju.USERID<0?0:Guguju.USERID);
        params.addProperty("auth", TextUtils.isEmpty(Guguju.AUTH) ? "" : Guguju.AUTH);
        params.addProperty("asessToken",  TextUtils.isEmpty(Guguju.ASESSTOKEN) ? "" : Guguju.ASESSTOKEN);
        return params;
    }
}
